<?php

namespace app\index\controller;

use app\BaseController;
use League\OAuth2\Server\Exception\OAuthServerException;


use League\OAuth2\Server\Middleware\ResourceServerMiddleware;
use League\OAuth2\Server\ResourceServer;



use app\index\Repositories\AccessTokenRepository;

class Api extends BaseController
{

    protected $server;

    // function initialize()
    // {



    // }



    // return new ResourceServer($accessTokenRepository, $publicKey);


    public function user()
    {
   
        $encryptionKeyPath = file_get_contents(app()->getRootPath() . 'app/index/config/key/public.key');

        $server = new ResourceServer(
            new AccessTokenRepository(),            // instance of AccessTokenRepositoryInterface
            file_get_contents(app()->getRootPath() . 'app/index/config/key/public.key')  // the authorization server's public key
        );

        $this->server = $server;
         


        // $publicKey = file_get_contents(app()->getRootPath() . 'app/index/config/key/public.key');
        // $accessTokenRepository = new AccessTokenRepository(
        //     new TokenRepository()
        // );

        // $this->server = new ResourceServer($accessTokenRepository, $publicKey);



        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;
        
           
        try {
            $request = $this->server->validateAuthenticatedRequest($request);
        } catch (OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        }

        // dump($request);
        // exit();





        $users = [
            [
                'id'    => 123,
                'name'  => 'Alex',
                'email' => 'alex@thephpleague.com',
            ],
            [
                'id'    => 124,
                'name'  => 'Frank',
                'email' => 'frank@thephpleague.com',
            ],
            [
                'id'    => 125,
                'name'  => 'Phil',
                'email' => 'phil@thephpleague.com',
            ],
        ];


        $totalUsers = count($users);

        

        // If the access token doesn't have the `basic` scope hide users' names
        if (!in_array('basic', $this->request->param())) {
            for ($i = 0; $i < $totalUsers; $i++) {
                unset($users[$i]['name']);
            }
        }

        // If the access token doesn't have the `email` scope hide users' email addresses
        if (!in_array('email', $this->request->param())) {
            for ($i = 0; $i < $totalUsers; $i++) {
                unset($users[$i]['email']);
            }
        }

        // print_r ($this->request->param());
        // exit();
        $response->getBody()->write(json_encode($users));

        return $response->withStatus(200);
    }
}
